//
//  PostWebView.m
//  PostDelivery
//
//  Created by wmz on 2020/6/21.
//  Copyright © 2020 wmz. All rights reserved.
//

#import "PostWebView.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "BaseVC.h"
@interface PostWebView()<WKNavigationDelegate,WKScriptMessageHandler>
@property(nonatomic, strong)WKUserContentController *userController;
@property(nonatomic, strong)UIProgressView *progressView;
@end
@implementation PostWebView

- (void)setUrl:(NSString *)url{
    _url = url;
    if (!url) return;
    [self layoutIfNeeded];
    self.myWebView.frame = self.bounds;
    self.backgroundColor = wColor_white;
    self.progressView.frame = CGRectMake(0, 0, self.bounds.size.width,20);
    [self addSubview:self.progressView];
    if ([url hasPrefix:@"http"]) {
        [self request];
    }else{
        if (self.sitHeight) {
            CGRect frame = self.myWebView.frame;
            frame.size.height = 0;
            self.myWebView.frame = frame;
        }
        NSString *headerString = @"<header><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'><style>img{max-width:100%}</style></header>";
        [self.myWebView loadHTMLString:[headerString stringByAppendingString:url]  baseURL:nil];
    }
}

- (UIProgressView *)progressView{
    if (!_progressView) {
        _progressView = UIProgressView.new;
    }
    return _progressView;
}

- (void)hd_setupViews{
    self.backgroundColor = [UIColor whiteColor];
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    self.userController = [[WKUserContentController alloc] init];
//    [self.userController addScriptMessageHandler:self name:@"back"];
    configuration.userContentController = self.userController;
    configuration.preferences.javaScriptEnabled = YES;
    configuration.preferences.javaScriptCanOpenWindowsAutomatically = YES;
    self.myWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
    self.myWebView.navigationDelegate = self;
    self.myWebView.opaque = NO;
    self.myWebView.multipleTouchEnabled = YES;
    self.myWebView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
    [self addSubview:self.myWebView];

    [self.myWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew| NSKeyValueObservingOptionOld context:nil];
    [self.myWebView addObserver:self forKeyPath:@"URL" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    
     if ([keyPath isEqual: @"estimatedProgress"] && object == self.myWebView) {
        [self.progressView setAlpha:1.0f];
        [self.progressView setProgress:self.myWebView.estimatedProgress animated:YES];
        if(self.myWebView.estimatedProgress >= 1.0f)
          {
            [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:NO];
            }];
        }
    }
}

- (void)request{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url]
                           cachePolicy:NSURLRequestReturnCacheDataElseLoad
                                   timeoutInterval:15.0];

    NSDictionary *cachedHeaders = [[NSUserDefaults standardUserDefaults] objectForKey:self.url];

    [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
           NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
           if ([[cachedHeaders objectForKey:@"Etag"] isEqualToString:[httpResponse.allHeaderFields objectForKey:@"Etag"]]&&
               [[cachedHeaders objectForKey:@"Last-Modified"] isEqualToString:[httpResponse.allHeaderFields objectForKey:@"Last-Modified"]]) {
               [request setCachePolicy:NSURLRequestReturnCacheDataElseLoad];
           }else{
               [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
           }
          [[NSUserDefaults standardUserDefaults] setObject:httpResponse.allHeaderFields forKey:self.url];
        // 重新刷新
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.myWebView loadRequest:request];
    });
    }] resume];
    
    [self.myWebView loadRequest:request];
}

- (void)setHideProgress:(BOOL)hideProgress{
    _hideProgress = hideProgress;
    if (hideProgress) {
        [self.myWebView removeObserver:self forKeyPath:@"estimatedProgress" context:nil];
        self.progressView.hidden = YES;
    }
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
}
#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    if ([[NSUserDefaults standardUserDefaults] doubleForKey:@"urlTime"]) {
        double time = [[NSUserDefaults standardUserDefaults] doubleForKey:@"urlTime"];
        double nowTime = [[NSDate date] timeIntervalSince1970];
        NSLog(@"耗时 %.2f 秒",nowTime-time);
    }
    if (self.sitHeight) {
        [webView evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id _Nullable result,NSError *_Nullable error) {
               //获取页面高度
            CGFloat scrollHeight = [result doubleValue];
            CGRect rect = self.myWebView.frame;
            rect.size.height = scrollHeight;
            self.myWebView.frame = rect;
            [GNEvent eventResponder:self target:webView key:@"webView" indexPath:nil info:@{@"height":@(scrollHeight)}];
        }];
    }
}

-(void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    
}
- (void)clearCache {
    NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];;
    NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
    }];
}
- (void)didReceiveMemoryWarning{
    [self clearCache];
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.myWebView setNavigationDelegate:nil];
    [self.myWebView setUIDelegate:nil];
}
@end
